<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 顶部导航栏 -->
    <header class="bg-white border-b border-gray-200 sticky top-0 z-50">
      <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex items-center justify-between h-16">
          <div class="flex items-center gap-3">
            <div class="w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center">
              <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
              </svg>
            </div>
            <span class="text-xl font-semibold text-gray-900">校园快递代拿</span>
            <span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded">下单者</span>
          </div>
          <button class="flex items-center gap-1 text-gray-600 hover:text-gray-900" @click="$router.push('/identity')">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2 20a10 10 0 1120 0H2z"/>
            </svg>
            <span>身份切换</span>
          </button>
        </div>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <main class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 面包屑 -->
      <div class="mb-6">
        <button class="text-sm text-gray-500 hover:text-blue-600" @click="$router.push('/order/my')">
          <svg class="w-4 h-4 inline mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
          </svg>
          返回我的订单
        </button>
      </div>

      <!-- 支付页面标题 -->
      <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-900 mb-2">订单支付</h1>
        <p class="text-gray-500">请确认订单信息并完成支付</p>
      </div>

      <!-- 订单信息卡片 -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6" v-if="orderInfo">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">订单信息</h2>
        <div class="space-y-3 border-b pb-4 mb-4">
          <div class="flex justify-between">
            <span class="text-gray-600">订单编号</span>
            <span class="text-gray-900 font-medium">{{ orderInfo.id }}</span>
          </div>
          <div class="flex justify-between">
            <span class="text-gray-600">取件码</span>
            <span class="text-gray-900 font-medium">{{ orderInfo.pickup_code || '—' }}</span>
          </div>
          <div class="flex justify-between">
            <span class="text-gray-600">取件地点</span>
            <span class="text-gray-900">{{ orderInfo.pickup_location || '—' }}</span>
          </div>
          <div class="flex justify-between">
            <span class="text-gray-600">送达地点</span>
            <span class="text-gray-900">{{ orderInfo.delivery_address || '—' }}</span>
          </div>
          <div class="flex justify-between">
            <span class="text-gray-600">订单状态</span>
            <span class="px-2 py-1 bg-blue-100 text-blue-700 text-xs rounded">{{ orderInfo.statusText || '—' }}</span>
          </div>
        </div>
        
        <!-- 费用明细 -->
        <div class="space-y-2 pt-4 border-t">
          <div class="flex justify-between text-sm">
            <span class="text-gray-600">订单金额</span>
            <span class="text-gray-900">¥{{ orderInfo.amount }}</span>
          </div>
          <div class="flex justify-between text-sm">
            <span class="text-gray-600">优惠折扣</span>
            <span class="text-green-600">-¥{{ (discount || 0).toFixed(2) }}</span>
          </div>
          <div class="flex justify-between text-lg font-semibold pt-2 border-t">
            <span class="text-gray-900">实付金额</span>
            <span class="text-blue-600">¥{{ actualAmount.toFixed(2) }}</span>
          </div>
        </div>
      </div>

      <!-- 支付方式选择 -->
      <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <h2 class="text-lg font-semibold text-gray-900 mb-4">选择支付方式</h2>
        <div class="space-y-3">
          <label class="flex items-center p-4 border-2 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors"
                 :class="paymentMethod === 'wechat' ? 'border-blue-600 bg-blue-50' : 'border-gray-200'">
            <input type="radio" v-model="paymentMethod" value="wechat" class="w-5 h-5 text-blue-600 focus:ring-blue-500 mr-4" />
            <div class="flex items-center gap-3 flex-1">
              <div class="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                <svg class="w-6 h-6 text-green-600" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M8.691 2.188C3.891 2.188 0 5.476 0 9.53c0 2.212 1.17 4.203 3.002 5.55a.59.59 0 0 1 .213.665l-.39 1.48c-.019.07-.048.141-.048.213 0 .163.13.295.29.295a.326.326 0 0 0 .167-.054l1.903-1.114a.864.864 0 0 1 .717-.098 10.16 10.16 0 0 0 2.837.403c.276 0 .543-.027.811-.05-.857-2.578.157-4.972 1.932-6.446 1.703-1.415 3.882-1.98 5.853-1.838-.576-3.583-4.196-6.153-8.597-6.153zM5.785 5.991c.642 0 1.162.529 1.162 1.18a1.17 1.17 0 0 1-1.162 1.178A1.17 1.17 0 0 1 4.623 7.17c0-.651.52-1.18 1.162-1.18zm5.813 0c.642 0 1.162.529 1.162 1.18a1.17 1.17 0 0 1-1.162 1.178 1.17 1.17 0 0 1-1.162-1.178c0-.651.52-1.18 1.162-1.18zm5.34 2.746c-1.693 0-3.152.978-3.816 2.396-.183.386-.291.813-.291 1.262 0 .14.018.277.043.41-1.253-.6-2.566-1.017-3.978-1.017-4.606 0-8.34 3.26-8.34 7.283 0 1.994.967 3.787 2.47 4.925a.443.443 0 0 1 .16.499l-.293 1.109c-.014.066-.036.132-.036.2 0 .122.098.221.219.221a.245.245 0 0 0 .125-.041l1.428-.836a.65.65 0 0 1 .538-.073c1.157.261 2.367.39 3.576.39 5.715 0 10.353-4.024 10.353-8.988 0-1.688-.626-3.244-1.68-4.47.203-.017.402-.04.618-.04 3.629 0 6.139 2.676 6.139 6.553 0 3.877-2.51 6.554-6.139 6.554-1.08 0-2.105-.243-3.025-.677-.461 1.283-1.453 2.311-2.714 2.998a.522.522 0 0 1-.235.054.52.52 0 0 1-.326-.114.515.515 0 0 1-.119-.367c0-.09.014-.181.036-.271l.288-1.088a.382.382 0 0 1 .144-.433c1.238-.831 2.09-2.11 2.442-3.577a.952.952 0 0 0 .065-.325c0-.413-.338-.748-.754-.748-.213 0-.411.09-.549.247-1.177 1.094-2.697 1.711-4.354 1.711z"/>
                </svg>
              </div>
              <div class="flex-1">
                <div class="font-medium text-gray-900">微信支付</div>
                <div class="text-sm text-gray-500">安全便捷的支付方式</div>
              </div>
            </div>
          </label>

          <label class="flex items-center p-4 border-2 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors"
                 :class="paymentMethod === 'alipay' ? 'border-blue-600 bg-blue-50' : 'border-gray-200'">
            <input type="radio" v-model="paymentMethod" value="alipay" class="w-5 h-5 text-blue-600 focus:ring-blue-500 mr-4" />
            <div class="flex items-center gap-3 flex-1">
              <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                <svg class="w-6 h-6 text-blue-600" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M21.714 7.424a.36.36 0 0 0-.106-.283l-.284-.283a.355.355 0 0 0-.282-.106h-2.895a.355.355 0 0 0-.283.106l-.283.283a.36.36 0 0 0-.106.283v2.895c0 .113.035.209.106.283l.283.283c.075.07.17.106.283.106h2.895a.355.355 0 0 0 .283-.106l.283-.283a.36.36 0 0 0 .106-.283V7.424zm-8.283-4.877a.355.355 0 0 0-.283-.106H10.253a.355.355 0 0 0-.283.106l-.283.283a.36.36 0 0 0-.106.283v2.895c0 .113.035.209.106.283l.283.283c.075.07.17.106.283.106h2.895a.355.355 0 0 0 .283-.106l.283-.283a.36.36 0 0 0 .106-.283V3.11zm8.283 0a.355.355 0 0 0-.283-.106h-2.895a.355.355 0 0 0-.283.106l-.283.283a.36.36 0 0 0-.106.283v2.895c0 .113.035.209.106.283l.283.283c.075.07.17.106.283.106h2.895a.355.355 0 0 0 .283-.106l.283-.283a.36.36 0 0 0 .106-.283V3.11zm0 8.283a.36.36 0 0 0-.106-.283l-.283-.283a.355.355 0 0 0-.282-.106h-2.895a.355.355 0 0 0-.283.106l-.283.283a.36.36 0 0 0-.106.283v2.895c0 .113.035.209.106.283l.283.283c.075.07.17.106.283.106h2.895a.355.355 0 0 0 .283-.106l.283-.283a.36.36 0 0 0 .106-.283v-2.895zm-8.283 0a.36.36 0 0 0-.106-.283l-.283-.283a.355.355 0 0 0-.282-.106H10.253a.355.355 0 0 0-.283.106l-.283.283a.36.36 0 0 0-.106.283v2.895c0 .113.035.209.106.283l.283.283c.075.07.17.106.283.106h2.895a.355.355 0 0 0 .283-.106l.283-.283a.36.36 0 0 0 .106-.283v-2.895zm-8.283 4.877a.355.355 0 0 0-.283-.106H3.11a.355.355 0 0 0-.283.106l-.283.283a.36.36 0 0 0-.106.283v2.895c0 .113.035.209.106.283l.283.283c.075.07.17.106.283.106h2.895a.355.355 0 0 0 .283-.106l.283-.283a.36.36 0 0 0 .106-.283v-2.895zm8.283 0a.355.355 0 0 0-.283-.106H10.253a.355.355 0 0 0-.283.106l-.283.283a.36.36 0 0 0-.106.283v2.895c0 .113.035.209.106.283l.283.283c.075.07.17.106.283.106h2.895a.355.355 0 0 0 .283-.106l.283-.283a.36.36 0 0 0 .106-.283v-2.895zm8.283 0a.355.355 0 0 0-.283-.106h-2.895a.355.355 0 0 0-.283.106l-.283.283a.36.36 0 0 0-.106.283v2.895c0 .113.035.209.106.283l.283.283c.075.07.17.106.283.106h2.895a.355.355 0 0 0 .283-.106l.283-.283a.36.36 0 0 0 .106-.283v-2.895z"/>
                </svg>
              </div>
              <div class="flex-1">
                <div class="font-medium text-gray-900">支付宝</div>
                <div class="text-sm text-gray-500">快速安全的支付方式</div>
              </div>
            </div>
          </label>

          <label class="flex items-center p-4 border-2 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors"
                 :class="paymentMethod === 'balance' ? 'border-blue-600 bg-blue-50' : 'border-gray-200'">
            <input type="radio" v-model="paymentMethod" value="balance" class="w-5 h-5 text-blue-600 focus:ring-blue-500 mr-4" />
            <div class="flex items-center gap-3 flex-1">
              <div class="w-10 h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                <svg class="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z"/>
                </svg>
              </div>
              <div class="flex-1">
                <div class="font-medium text-gray-900">账户余额</div>
                <div class="text-sm text-gray-500">账户余额：¥{{ userBalance.toFixed(2) }}</div>
              </div>
            </div>
          </label>
        </div>
      </div>

      <!-- 支付协议 -->
      <div class="mb-6">
        <label class="flex items-start gap-2 cursor-pointer">
          <input type="checkbox" v-model="agreed" class="w-5 h-5 text-blue-600 rounded focus:ring-blue-500 mt-0.5" />
          <span class="text-sm text-gray-600">我已阅读并同意 <a href="#" class="text-blue-600 hover:underline">《支付协议》</a> 和 <a href="#" class="text-blue-600 hover:underline">《服务条款》</a></span>
        </label>
      </div>

      <!-- 支付按钮 -->
      <div class="bg-white rounded-lg shadow-sm p-6">
        <div class="flex items-center justify-between mb-6">
          <span class="text-lg text-gray-700">需支付金额</span>
          <span class="text-3xl font-bold text-blue-600">¥{{ actualAmount.toFixed(2) }}</span>
        </div>
        <button 
          @click="handlePayment" 
          :disabled="!paymentMethod || !agreed || isPaying"
          class="w-full py-4 bg-blue-600 text-white rounded-lg font-semibold text-lg hover:bg-blue-700 transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed flex items-center justify-center gap-2"
        >
          <svg v-if="isPaying" class="animate-spin h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          <span>{{ isPaying ? '支付中...' : '确认支付' }}</span>
        </button>
        <p class="text-xs text-gray-500 text-center mt-4">
          支付完成后，订单将自动更新为"已完成"状态
        </p>
      </div>

      <!-- 安全提示 -->
      <div class="mt-6 p-4 bg-blue-50 rounded-lg border border-blue-200">
        <div class="flex items-start gap-3">
          <svg class="w-5 h-5 text-blue-600 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/>
          </svg>
          <div class="text-sm text-blue-800">
            <p class="font-medium mb-1">支付安全提示</p>
            <p>本平台采用加密传输技术，保障您的支付安全。如遇到任何问题，请及时联系客服。</p>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Payment',
  data() {
    return {
      orderId: null,
      orderInfo: null,
      paymentMethod: 'wechat',
      agreed: false,
      discount: 0,
      userBalance: 0,
      isPaying: false
    }
  },
  computed: {
    actualAmount() {
      const amount = Number(this.orderInfo?.amount || 0)
      return Math.max(0, amount - this.discount)
    }
  },
  async mounted() {
    this.orderId = this.$route.params.orderId || this.$route.query.orderId
    if (!this.orderId) {
      alert('订单ID缺失')
      this.$router.push('/order/my')
      return
    }
    await this.fetchOrderInfo()
    await this.fetchUserBalance()
  },
  methods: {
    async fetchOrderInfo() {
      try {
        const { data } = await axios.get(`/api/orders/${this.orderId}`)
        if (data && data.success !== false) {
          const d = data.data || {}
          // 动态获取费用字段
          const amount = Number(d.final_fee ?? d.suggested_fee ?? d.amount ?? d.fee ?? 0)
          const status = Number(d.status)
          let statusText = '—'
          if (status === 0) statusText = '待接单'
          else if (status === 1) statusText = '已接单'
          else if (status === 2) statusText = '已取件'
          else if (status === 3) statusText = '配送中'
          else if (status === 4) statusText = '已送达'
          else if (status === 5) statusText = '已完成'
          else if (status === 6) statusText = '已取消'

          this.orderInfo = {
            id: d.id,
            pickup_code: d.pickup_code || '—',
            pickup_location: d.pickup_location || '—',
            delivery_address: d.delivery_address || '—',
            amount: amount.toFixed(2),
            status,
            statusText
          }
        }
      } catch (e) {
        console.error('获取订单信息失败', e)
        alert('获取订单信息失败，请稍后再试')
        this.$router.push('/order/my')
      }
    },
    async fetchUserBalance() {
      const userId = localStorage.getItem('userId')
      if (!userId) return
      try {
        const { data } = await axios.get(`/api/payments/balance/${userId}`)
        if (data && data.success !== false) {
          this.userBalance = Number(data.data?.balance || 0)
        }
      } catch (e) {
        console.error('获取账户余额失败', e)
      }
    },
    async handlePayment() {
      if (!this.paymentMethod || !this.agreed) {
        alert('请选择支付方式并同意支付协议')
        return
      }

      if (this.paymentMethod === 'balance' && this.userBalance < this.actualAmount) {
        alert('账户余额不足，请选择其他支付方式')
        return
      }

      if (!confirm(`确认使用${this.paymentMethod === 'wechat' ? '微信支付' : this.paymentMethod === 'alipay' ? '支付宝' : '账户余额'}支付 ¥${this.actualAmount.toFixed(2)} 吗？`)) {
        return
      }

      this.isPaying = true
      try {
        // 调用支付接口
        const userId = localStorage.getItem('userId')
        const { data } = await axios.post('/api/payments/create', {
          order_id: this.orderId,
          user_id: userId,
          amount: this.actualAmount,
          payment_method: this.paymentMethod,
          discount: this.discount,
          openid: localStorage.getItem('wechat_openid') || null // 如果在微信内，传递openid
        })

        if (data && data.success !== false) {
          // 根据支付方式处理
          if (this.paymentMethod === 'balance') {
            // 余额支付直接完成
            alert('支付成功！')
            this.$router.push('/order/my')
          } else if (this.paymentMethod === 'wechat') {
            // 微信支付
            const paymentType = data?.data?.paymentType
            if (paymentType === 'wechat_jsapi') {
              // JSAPI支付（在微信内）
              await this.callWechatJSAPI(data.data.params)
            } else if (paymentType === 'wechat_h5') {
              // H5支付（跳转到支付页面）
              window.location.href = data.data.paymentUrl
            } else if (paymentType === 'mock') {
              // 后端微信配置缺失时的“模拟支付”，直接视为支付成功
              alert('模拟支付成功！')
              this.isPaying = false
              this.$router.push('/order/my')
            } else {
              // 兜底：返回了 success 但没有可识别的支付类型，直接按成功处理
              alert('支付已处理成功！')
              this.isPaying = false
              this.$router.push('/order/my')
            }
          } else if (this.paymentMethod === 'alipay') {
            // 支付宝支付（使用表单提交方式，更可靠）
            if (data.data.formHtml) {
              // 使用表单HTML提交
              const formWindow = window.open('', '_blank')
              formWindow.document.write(data.data.formHtml)
              formWindow.document.close()
            } else {
              // 如果没有表单HTML，使用URL跳转
              window.location.href = data.data.paymentUrl
            }
          }
        } else {
          throw new Error(data.message || '支付失败')
        }
      } catch (e) {
        console.error('支付失败', e)
        alert(e.response?.data?.message || e.message || '支付失败，请稍后再试')
        this.isPaying = false
      }
    },
    // 调用微信JSAPI支付
    callWechatJSAPI(params) {
      return new Promise((resolve, reject) => {
        // 检查是否在微信环境
        if (typeof WeixinJSBridge === 'undefined') {
          // 动态加载微信JS-SDK
          if (typeof window.wx === 'undefined') {
            const script = document.createElement('script')
            script.src = 'https://res.wx.qq.com/open/js/jweixin-1.6.0.js'
            script.onload = () => this.executeWechatPay(params, resolve, reject)
            script.onerror = () => reject(new Error('加载微信JS-SDK失败'))
            document.head.appendChild(script)
          } else {
            this.executeWechatPay(params, resolve, reject)
          }
        } else {
          // 使用旧版 WeixinJSBridge
          WeixinJSBridge.invoke('getBrandWCPayRequest', params, (res) => {
            if (res.err_msg === 'get_brand_wcpay_request:ok') {
              alert('支付成功！')
              this.$router.push('/order/my')
              resolve(res)
            } else {
              reject(new Error('支付失败: ' + res.err_msg))
            }
          })
        }
      })
    },
    // 执行微信支付
    executeWechatPay(params, resolve, reject) {
      // 使用微信JS-SDK调用支付
      if (typeof window.wx !== 'undefined') {
        window.wx.chooseWXPay({
          timestamp: params.timeStamp,
          nonceStr: params.nonceStr,
          package: params.package,
          signType: params.signType,
          paySign: params.paySign,
          success: () => {
            alert('支付成功！')
            this.$router.push('/order/my')
            resolve()
          },
          cancel: () => {
            alert('支付已取消')
            this.isPaying = false
            reject(new Error('用户取消支付'))
          },
          fail: (err) => {
            alert('支付失败: ' + (err.errMsg || '未知错误'))
            this.isPaying = false
            reject(new Error(err.errMsg || '支付失败'))
          }
        })
      } else {
        reject(new Error('微信JS-SDK未加载'))
      }
    }
  }
}
</script>

